package com.xzzz.backend.bsms.server.rbac.sys.captcha;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.xzzz.common.base.enums.YesNo;
import com.xzzz.common.base.exception.XzException;
import com.xzzz.common.base.exception.XzException400;
import com.xzzz.common.base.pojo.RCode;
import com.xzzz.common.base.util.spring.SpringUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@AllArgsConstructor
public class CaptchaPhoneService {

    private final StringRedisTemplate redisTemplate;
    private static final long captchaLimitTimeout = 60L;
    private static final long captchaTimeout = 15 * 60;

    /**
     * 短信验证码KEY
     */
    public String buildKey(String phone) {
        return SpringUtil.getAppName() + ":captcha_phone:" + phone;
    }

    /**
     * 短信频繁KEY
     */
    public String buildLimitKey(String phone) {
        return SpringUtil.getAppName() + ":captcha_phone_limit:" + phone;
    }

    /**
     * 发送短信验证码, 保留15分钟
     *
     * @param phone 手机号
     */
    public void send(String phone) {
        XzException400.throwBy(StrUtil.isBlank(phone), "手机号不得为空");

        String limit = redisTemplate.opsForValue().get(buildLimitKey(phone));
        if (YesNo.YES.getName().equals(limit)) {
            throw new XzException(RCode.TOO_MANY_SEND_SMS);
        }

        String captchaCode = String.valueOf(RandomUtil.randomInt(100000, 999999));
//        PhoneMsgReq req = new PhoneMsgReq();
//        req.setId(String.valueOf(PrimaryKeyUtil.nextId()));
//        req.setTemplate("captchaCode");
//        req.setContent(String.format("{\"number\":\"%s\"}", captchaCode));
//        req.setReceiverPhone(phone);
//        smsManager.send(req);
        redisTemplate.opsForValue().set(buildLimitKey(phone), YesNo.YES.getName(), captchaLimitTimeout, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(buildKey(phone), captchaCode, captchaTimeout, TimeUnit.SECONDS);
    }

    /**
     * 消费验证码
     *
     * @param phone   手机号
     * @param captcha 验证码
     */
    public boolean consume(String phone, String captcha) {
        if (StrUtil.isBlank(phone) || StrUtil.isBlank(captcha)) {
            return false;
        }
        String cacheCaptcha = redisTemplate.opsForValue().get(buildKey(phone));
        if (StrUtil.isBlank(cacheCaptcha) || !captcha.equals(cacheCaptcha)) {
            return false;
        }
        return true;
    }
}
